<template>
  <div class="container">
    <el-row :gutter="20">
      <!-- 左侧地区选择部分 -->
      <!-- <el-col :span="6">
				<div class="region-section">
					<el-input v-model="input" placeholder="请输入内容"></el-input>
					<el-tree style="margin-top: 20px" ref="tree" :data="datas" :props="defaultProps" node-key="id"
						:highlight-current="true" :check-strictly="true" :filter-node-method="filterNode" :accordion="true"
						@node-click="handleNodeClick">
					</el-tree>
				</div>
			</el-col> -->

      <!-- 右侧线路管理部分 -->
      <el-col :span="24">
        <div class="line-section">
          <!-- 顶部筛选区域 -->
          <div class="filter-area" style="font-size: 14px; margin-bottom: 20px">
            <div class="filter-row">
              <div class="filter-item">
                <span class="filter-label">线路类型:</span>
                <el-select v-model="lineTypeFilter" placeholder="请选择线路类型" clearable @change="handleLineTypeChange"
                  @clear="handleFilterClear" style="width: 150px;">
                  <el-option v-for="item in lineTypeOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </div>
              <div class="filter-item">
                <span class="filter-label">线路搜索:</span>
                <div class="line-search-input">
                  <el-input v-model="searchParams.start_title" placeholder="选择开始地点" clearable style="width: 120px;"
                    @click="showStartLocationDialog = true">
                  </el-input>
                  <span class="line-separator">至</span>
                  <el-input v-model="searchParams.end_title" placeholder="选择结束地点" clearable style="width: 120px;"
                    @click="showEndLocationDialog = true">
                  </el-input>
                </div>
              </div>
              <div class="filter-item">
                <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
                <el-button size="small" @click="handleReset">重置</el-button>
              </div>
            </div>
          </div>

          <!-- 操作按钮和信息区域 -->
          <div>
            <div class="operation-area">
              <el-button type="primary" size="mini" icon="el-icon-plus" class="new-btn"
                @click="dialogVisible = true">新建</el-button>
              <span class="search-info" style="font-size: 14px; color: #1890ff" @click="openUnpricedDialog">用户搜索未定价线路（{{
                totalUnpricedRoutes }}）</span>
            </div>
            <!-- <p class="line-info" style="font-size: 14px">
              当前线路{{ lineData.length }}条，默认往返同价
            </p> -->
          </div>

          <!-- 线路表格 -->
          <avue-crud :option="lineOption" :table-loading="loading" :data="filteredLineData" :page.sync="page"
            v-model="form" ref="crud" @current-change="handlePageChange" @size-change="handleSizeChange">

            <!-- 自定义操作列 -->
            <template #menu="{ row, index, size }">

              <el-button type="danger" :size="'mini'" icon="el-icon-delete" @click="rowDel(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>

              <el-button :size="'mini'" icon="el-icon-edit" @click="edit(row)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
            </template>

            <!--
						<template #menu="{ row, index, size }">

							<el-button type="danger" :size="'mini'" icon="el-icon-delete" @click="rowDel(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>

							<el-button :size="'mini'" @click="shenhe(row)" style="width: 23px;
        height: 22px; padding: 0;">审核</el-button>
						</template> -->
            <!-- 自定义系统推荐价格列 -->
            <template slot="rec_price" slot-scope="scope">
              <span v-if="scope.row.rec_price" style="color: #f56c6c">¥{{ scope.row.rec_price }}</span>
              <span v-else style="color: #909399">未定价</span>
            </template>
          </avue-crud>
        </div>
      </el-col>
    </el-row>

    <!-- 新建/编辑线路弹框 -->
    <el-dialog :title="isEdit ? '编辑线路价格' : '新建线路'" :visible.sync="dialogVisible" width="60%"
      custom-class="custom-dialog" :modal-append-to-body="false" @open="handleDialogOpen" @close="handleDialogClose">
      <el-form ref="form" :model="formData" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="线路类型">
              <!-- 编辑模式：显示线路类型，不可选择 -->
              <template v-if="isEdit">
                <span class="type-display">{{ formData.type === 2 ? '城际线路' : '城乡线路' }}</span>
              </template>
              <!-- 新建模式：可选择线路类型 -->
              <template v-else>
                <el-select v-model="formData.type" placeholder="请选择线路类型" @change="handleTypeChange"
                  style="width: 100%;">
                  <el-option v-for="item in lineTypeOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </template>
            </el-form-item>
            <!-- 城市选择 - 仅城乡线路显示且非编辑模式 -->
            <el-form-item label="城市" v-if="formData.type === 1 && !isEdit">
              <el-select v-model="formData.city" placeholder="请选择城市" filterable clearable @change="handleCityChange">
                <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理商">
              <!-- 编辑模式：如果已有代理商则显示为只读 -->
              <template v-if="isEdit && formData.agent_id && formData.agent_id !== 0">
                <span class="type-display">{{ getAgentName(formData.agent_id) }}</span>
              </template>
              <!-- 新建模式或无代理商时：可选择代理商 -->
              <template v-else>
                <el-select v-model="formData.agent_id" placeholder="请选择代理商" @change="handleAgentChange"
                  style="width: 100%;">
                  <el-option v-for="item in agentList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </el-form-item>
            <el-form-item label="代理有效期">
              <el-date-picker v-model="formData.end_time" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date"
                placeholder="请选择代理有效期" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>



        <!-- 线路表格区域 -->
        <div class="line-table-container">
          <el-table :data="formData.lineItems" border style="width: 100%" class="line-items-table">
            <el-table-column label="线路" align="center">
              <template slot-scope="scope">
                <div class="line-select-container">
                  <!-- 编辑模式：显示路线信息，不可选择 -->
                  <template v-if="isEdit">
                    <span class="line-display">{{ scope.row.startTitle }}</span>
                    <span class="line-separator">-</span>
                    <span class="line-display">{{ scope.row.endTitle }}</span>
                  </template>
                  <!-- 新建模式：可选择路线 -->
                  <template v-else>
                    <el-select v-model="scope.row.start" :placeholder="formData.type === 1 ? '请选择城乡' : '请选择市县'"
                      filterable clearable class="line-select">
                      <!-- 城际线路选项 -->
                      <el-option v-for="item in cachedIntercityOptions" :key="item.id" :label="item.name"
                        :value="item.id" v-show="formData.type === 2" />
                      <!-- 城乡线路选项 -->
                      <el-option v-for="item in (cachedUrbanRuralOptions[formData.city] || [])" :key="item.id"
                        :label="item.name" :value="item.id" v-show="formData.type === 1 && formData.city" />
                    </el-select>
                    <span class="line-separator">-</span>
                    <el-select v-model="scope.row.end" :placeholder="formData.type === 1 ? '请选择城乡' : '请选择市县'" filterable
                      clearable class="line-select">
                      <!-- 城际线路选项 -->
                      <el-option v-for="item in cachedIntercityOptions" :key="item.id" :label="item.name"
                        :value="item.id" v-show="formData.type === 2" />
                      <!-- 城乡线路选项 -->
                      <el-option v-for="item in (cachedUrbanRuralOptions[formData.city] || [])" :key="item.id"
                        :label="item.name" :value="item.id" v-show="formData.type === 1 && formData.city" />
                    </el-select>
                  </template>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="系统推荐价格" width="180" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.recommendPrice" placeholder="请输入价格" type="number" min="0" />
              </template>
            </el-table-column>
            <el-table-column label="价格波动范围" width="180" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.priceWave" placeholder="请输入波动范围" type="number" min="0" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center" v-if="!isEdit">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleAddLineItem"
                  v-if="scope.$index === formData.lineItems.length - 1">
                  添加
                </el-button>
                <el-button type="text" size="small" @click="handleRemoveLineItem(scope.$index)"
                  v-if="formData.lineItems.length > 1">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 开始地点选择弹框 -->
    <el-dialog title="选择开始地点" :visible.sync="showStartLocationDialog" width="400px" custom-class="custom-dialog"
      :modal-append-to-body="false">
      <el-input v-model="searchParams.start_title" placeholder="请输入开始地点" clearable></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showStartLocationDialog = false">取 消</el-button>
        <el-button type="primary" @click="showStartLocationDialog = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 结束地点选择弹框 -->
    <el-dialog title="选择结束地点" :visible.sync="showEndLocationDialog" width="400px" custom-class="custom-dialog"
      :modal-append-to-body="false">
      <el-input v-model="searchParams.end_title" placeholder="请输入结束地点" clearable></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEndLocationDialog = false">取 消</el-button>
        <el-button type="primary" @click="showEndLocationDialog = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户搜索未定价线路弹框 -->
    <el-dialog title="用户搜索未定价线路" :visible.sync="unpricedDialogVisible" width="80%" custom-class="custom-dialog"
      :modal-append-to-body="false" @close="handleUnpricedDialogClose">
      <div class="unpriced-routes-container">
        <el-table :data="unpricedRoutesData" style="width: 100%" border>
          <el-table-column prop="line" label="线路" width="160" />
          <el-table-column prop="type_text" label="线路类型" width="160" />
          <el-table-column label="系统推荐价格" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.input_rec_price" placeholder="请输入价格" type="number" min="0"
                @keyup.enter.native="handleSubmitPrice(scope.row)">
                <template slot="prepend" v-if="scope.row.rec_price">
                  ¥{{ scope.row.rec_price }}
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="价格波动范围" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.input_wave_price" placeholder="请输入波动范围" type="number" min="0"
                @keyup.enter.native="handleSubmitPrice(scope.row)">
                <template slot="prepend" v-if="scope.row.allow_price_wave">
                  ¥{{ scope.row.allow_price_wave }}
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="primary" size="small" :loading="scope.row.submitting"
                @click="handleSubmitPrice(scope.row)">
                提交
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination @size-change="handleUnpricedSizeChange" @current-change="handleUnpricedCurrentChange"
            :current-page="unpricedCurrentPage" :page-sizes="[10, 20, 30, 50]" :page-size="unpricedPageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="totalUnpricedRoutes" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getPathList, getUserSearch, getAreaTree, addLineTpl, updateLinePrice, delShopItem, editLinePrice, getAgentList } from './api/pathmannage';

export default {
  data () {
    return {
      input: '',
      input_price: '',
      datas: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      dialogVisible: false,
      unpricedDialogVisible: false,
      isEdit: false, // 是否为编辑模式
      editId: null, // 编辑的记录ID
      formData: {
        type: '', // 改为使用type字段
        city: '',
        agent_id: '', // 代理商ID
        end_time: '', // 代理有效期
        lineItems: [
          {
            start: '',
            end: '',
            recommendPrice: '',
            priceWave: 100, // 默认价格波动范围
          },
        ],
      },

      // 线路管理相关数据
      lineTypeFilter: '', // 默认不选择任何线路类型
      lineTypeOptions: [
        { value: 2, label: '城际线路' }, // value改为2对应type
        { value: 1, label: '城乡线路' }, // value改为1对应type
      ],
      // 搜索参数
      searchParams: {
        start_title: '',
        end_title: '',
      },
      // 地点选择弹框
      showStartLocationDialog: false,
      showEndLocationDialog: false,
      lineOption: {
        title: false,
        border: true,
        index: true,
        indexLabel: '序号',
        menu: true,
        addBtn: false,
        searchBtn: false,
        searchShowBtn: false,
        stripe: true,
        highlightCurrentRow: true,
        viewBtn: false,
        delBtn: false,
        editBtn: false,

        column: [
          {
            label: '线路',
            prop: 'line',
            minWidth: 180,
            align: 'center',
          },
          {
            label: '线路类型',
            prop: 'type_text',
            minWidth: 120,
            align: 'center',
            filters: [
              { text: '城际线路', value: 2 }, // 改为使用type值
              { text: '城乡线路', value: 1 }, // 改为使用type值
            ],
            filterMethod: (value, row) => row.type === value,
          },
          {
            label: '代理商',
            prop: 'agent_name',
            minWidth: 120,
            align: 'center',
          },
          {
            label: '系统推荐价格',
            prop: 'rec_price',
            slot: true,
            minWidth: 150,
            align: 'center',
          },
          {
            label: '价格波动范围',
            prop: 'allow_price_wave',
            minWidth: 150,
            align: 'center',
          },
        ],
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },
      loading: false,
      lineData: [],
      queryParams: {
        // 第一次请求不传type参数，只有在用户主动选择时才传递
      },

      // 地区数据
      areaTreeData: [],
      cityOptions: [],
      countyOptions: [],
      townOptions: [],

      // 未定价线路相关
      unpricedRoutesData: [],
      unpricedCurrentPage: 1,
      unpricedPageSize: 10,
      totalUnpricedRoutes: 0,

      // 代理商列表
      agentList: [],

      // 预缓存的地点选项数据
      cachedIntercityOptions: [], // 城际线路选项
      cachedUrbanRuralOptions: {}, // 城乡线路选项，按城市ID缓存
    };
  },
  computed: {
    ...mapGetters(['permission']),
    filteredLineData () {
      // 直接返回lineData，因为已经通过API参数进行了筛选
      return this.lineData;
    },
    permissionList () {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
      };
    },

  },
  watch: {
    input (val) {
      this.$refs.tree.filter(val);
    },
  },
  async created () {
    await this.getAgentListData(); // 先获取代理商列表
    this.fetchLineList(); // 再获取线路列表
    this.getAreaTreeData();
  },
  methods: {
    edit (row) {
      console.log('编辑数据:', row);
      this.isEdit = true;
      this.editId = row.id;

      // 回显数据
      this.formData = {
        type: row.type,
        city: row.city_id || '',
        agent_id: row.agent_id || '', // 回显代理商ID
        end_time: row.end_time ? row.end_time.split(' ')[0] : '', // 回显代理有效期，只取日期部分
        lineItems: [
          {
            start: row.start_id,
            end: row.end_id,
            startTitle: row.start_title, // 添加起点标题
            endTitle: row.end_title, // 添加终点标题
            recommendPrice: row.rec_price,
            priceWave: row.allow_price_wave || 100,
          },
        ],
      };

      this.dialogVisible = true;
    },
    rowDel (row) {
      this.$confirm('确定将选择数据删除?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
      })
        .then(() => {
          return delShopItem(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },

    // 获取地区树数据
    async getAreaTreeData () {
      try {
        const res = await getAreaTree();
        this.datas = this.transformAreaData(res.data);
        this.parseAreaData(res.data);
      } catch (error) {
        console.error('获取地区树失败:', error);
        this.$message.error('获取地区数据失败');
      }
    },

    // 解析地区数据
    parseAreaData (data) {
      data.forEach(province => {
        if (province.children) {
          province.children.forEach(city => {
            this.cityOptions.push({
              id: city.id,
              name: city.name,
              type: city.type,
            });

            if (city.children) {
              city.children.forEach(county => {
                this.countyOptions.push({
                  id: county.id,
                  name: county.name,
                  parentId: city.id,
                  type: county.type,
                });

                if (county.children) {
                  county.children.forEach(town => {
                    this.townOptions.push({
                      id: town.id,
                      name: town.name,
                      parentId: county.id,
                      type: town.type,
                    });
                  });
                }
              });
            }
          });
        }
      });

      // 预缓存地点选项数据
      this.cacheLocationOptions();
    },

    // 转换地区数据格式
    transformAreaData (areaData) {
      return areaData.map(province => ({
        id: province.id,
        label: province.name,
        code: province.code,
        level: province.level,
        type: province.type,
        children: province.children ? this.transformAreaData(province.children) : [],
      }));
    },

    // 获取线路列表
    async fetchLineList () {
      this.loading = true;
      try {
        const params = {
          page: this.page.currentPage,
          size: this.page.pageSize,
          ...this.queryParams,
          ...this.searchParams,
        };
        const res = await getPathList(params);
        this.lineData = res.data.list.map(item => ({
          ...item, // 保留所有原始数据
          id: item.id,
          line: this.formatLineName(item.start_title, item.end_title),
          type_text: item.type === 2 ? '城际线路' : '城乡线路', // 根据type生成type_text
          agent_name: this.getAgentName(item.agent_id), // 添加代理商名称，为空时不显示任何内容
          rec_price: item.rec_price,
          allow_price_wave: item.allow_price_wave,
        }));
        this.page.total = res.data.total;
      } catch (error) {
        console.error('获取线路列表失败:', error);
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },

    // 获取未定价线路
    async fetchUnpricedRoutes () {
      try {
        this.loading = true;
        const params = {
          current: this.unpricedCurrentPage,
          size: this.unpricedPageSize,
        };
        const res = await getUserSearch(params);
        this.unpricedRoutesData = res.data.list.map(item => ({
          ...item,
          line: this.formatLineName(item.start_title, item.end_title),
          type_text: item.type === 2 ? '城际线路' : '城乡线路', // 根据type生成type_text
          input_rec_price: item.rec_price || '',
          input_wave_price: item.allow_price_wave || '',
          submitting: false, // 添加提交状态
        }));
        this.totalUnpricedRoutes = res.data.total;
      } catch (error) {
        console.error('获取用户搜索未定价线路失败:', error);
        this.$message.error('获取未定价线路数据失败');
      } finally {
        this.loading = false;
      }
    },

    // 格式化线路名称
    formatLineName (startCity, endCity) {
      if (!startCity && !endCity) return '未知线路';
      return `${startCity || '未知'}-${endCity || '未知'}`;
    },

    // 树节点过滤
    filterNode (value, data) {
      if (!value) return true;
      return data.label.includes(value);
    },

    // 树节点点击
    handleNodeClick (data) {
      this.$refs.tree.setCurrentKey(data.id);
    },

    // 线路类型筛选变化
    handleLineTypeChange (val) {
      if (val) {
        // 只有在用户选择了有效值时才传递type参数
        this.queryParams.type = val;
      } else {
        // 如果用户清空了选择，则不传递type参数
        delete this.queryParams.type;
      }
      this.page.currentPage = 1;
      this.fetchLineList();
    },

    // 清空筛选
    handleFilterClear () {
      this.queryParams = {};
      this.lineTypeFilter = '';
      this.fetchLineList();
    },

    // 查询
    handleSearch () {
      this.page.currentPage = 1;
      this.fetchLineList();
    },

    // 重置
    handleReset () {
      // 保留线路类型筛选，只重置搜索参数
      this.searchParams = {
        start_title: '',
        end_title: '',
      };
      // 清空queryParams中除了type之外的其他参数
      const type = this.queryParams.type;
      this.queryParams = type ? { type } : {};
      this.page.currentPage = 1;
      this.fetchLineList();
    },

    // 打开对话框
    async handleDialogOpen () {
      // 确保代理商列表已加载
      if (this.agentList.length === 0) {
        await this.getAgentListData();
      }

      // 确保地点数据已预缓存
      if (this.cachedIntercityOptions.length === 0) {
        this.cacheLocationOptions();
      }

      // 如果不是编辑模式，重置表单数据
      if (!this.isEdit) {
        this.formData = {
          type: '',
          city: '',
          agent_id: '', // 重置代理商选择
          end_time: '', // 重置代理有效期
          lineItems: [
            {
              start: '',
              end: '',
              recommendPrice: '',
              priceWave: 100, // 默认价格波动范围
            },
          ],
        };
      }
    },

    // 关闭对话框
    handleDialogClose () {
      // 重置编辑状态
      this.isEdit = false;
      this.editId = null;
    },

    // 打开未定价线路对话框
    openUnpricedDialog () {
      this.unpricedDialogVisible = true;
      this.unpricedCurrentPage = 1;
      this.fetchUnpricedRoutes();
    },

    // 关闭未定价线路对话框
    handleUnpricedDialogClose () {
      this.unpricedRoutesData = [];
    },

    // 线路类型变化
    handleTypeChange (val) {
      // 只更新线路类型，其他数据保持不变
      this.formData.type = val;

      // 如果是城乡线路，清空城市选择
      if (val === 1) {
        this.formData.city = '';
      }

      // 清空线路选择，但保留价格设置
      this.formData.lineItems.forEach(item => {
        item.start = '';
        item.end = '';
        // 保留推荐价格和价格波动范围
      });
    },

    // 预缓存地点选项数据
    cacheLocationOptions () {
      // 缓存城际线路选项（所有城市和县区）
      this.cachedIntercityOptions = [...this.cityOptions, ...this.countyOptions];

      // 缓存城乡线路选项（按城市分组）
      this.cachedUrbanRuralOptions = {};
      this.cityOptions.forEach(city => {
        const counties = this.countyOptions.filter(c => c.parentId === city.id);
        const countyIds = counties.map(c => c.id);
        const towns = this.townOptions.filter(t => countyIds.includes(t.parentId));
        this.cachedUrbanRuralOptions[city.id] = [...counties, ...towns];
      });
    },

    // 城市选择变化
    handleCityChange () {
      // 只清空线路选择，保留价格设置
      this.formData.lineItems.forEach(item => {
        item.start = '';
        item.end = '';
      });
    },

    // 获取代理商名称
    getAgentName (agentId) {
      if (!agentId || agentId === 0) return undefined; // 如果没有代理商ID或ID为0，返回undefined
      const agent = this.agentList.find(item => item.value === agentId);
      return agent ? agent.label : undefined; // 如果没找到代理商，返回undefined
    },

    // 代理商选择变化
    handleAgentChange () {
      // 代理商选择变化时的处理逻辑
    },

    // 添加线路项
    handleAddLineItem () {
      this.formData.lineItems.push({
        start: '',
        end: '',
        recommendPrice: '',
        priceWave: 100, // 默认价格波动范围
      });
    },

    // 移除线路项
    handleRemoveLineItem (index) {
      if (this.formData.lineItems.length > 1) {
        this.formData.lineItems.splice(index, 1);
      } else {
        this.$message.warning('至少需要保留一条线路');
      }
    },



    async submitForm () {
      console.log(this.formData, "this.formData-------------");
      // 验证表单数据
      if (!this.formData.type) {
        this.$message.warning('请选择线路类型');
        return;
      }

      // 验证代理商和有效期
      if (this.formData.agent_id && this.formData.agent_id !== 0 && !this.formData.end_time) {
        this.$message.warning('选择了代理商，请同时选择代理有效期');
        return;
      }

      // 验证每条线路
      for (const item of this.formData.lineItems) {
        if (!this.isEdit) {
          // 新建模式需要验证路线信息
          if (!item.start || !item.end) {
            this.$message.warning('请填写完整的线路信息');
            return;
          }

          if (item.start === item.end) {
            this.$message.warning('起点和终点不能相同');
            return;
          }
        }

        if (!item.recommendPrice) {
          this.$message.warning('请输入推荐价格');
          return;
        }

        if (!item.priceWave) {
          this.$message.warning('请输入价格波动范围');
          return;
        }
      }

      try {
        if (this.isEdit) {
          // 编辑模式 - 只处理第一条线路（编辑时只有一条）
          const item = this.formData.lineItems[0];
          const submitData = {
            id: this.editId, // 添加编辑ID
            type: this.formData.type,
            start_id: item.start,
            end_id: item.end,
            rec_price: item.recommendPrice,
            allow_price_wave: item.priceWave,
            agent_id: this.formData.agent_id || 0, // 添加代理商ID，不选择时传0
            end_time: this.formData.end_time || '', // 添加代理有效期
          };
          await editLinePrice(submitData);
          this.$message.success('编辑线路成功');
        } else {
          // 新建模式 - 为每条线路单独提交
          const promises = this.formData.lineItems.map(item => {
            const submitData = {
              type: this.formData.type,
              start_id: item.start,
              end_id: item.end,
              rec_price: item.recommendPrice,
              allow_price_wave: item.priceWave,
              agent_id: this.formData.agent_id || 0, // 添加代理商ID，不选择时传0
              end_time: this.formData.end_time || '', // 添加代理有效期
            };
            return addLineTpl(submitData);
          });
          await Promise.all(promises);
          this.$message.success('新建线路成功');
        }

        this.dialogVisible = false;
        this.fetchLineList();
      } catch (error) {
        this.$message.error(this.isEdit ? '编辑线路失败' : '新建线路失败');
        console.error(error);
      }
    },

    // 提交价格
    async handleSubmitPrice (row) {
      if (!row.input_rec_price) {
        this.$message.warning('请输入推荐价格');
        return;
      }

      if (!row.input_wave_price) {
        this.$message.warning('请输入价格波动范围');
        return;
      }

      try {
        // 设置提交状态
        row.submitting = true;

        const submitData = {
          id: row.id,
          rec_price: parseFloat(row.input_rec_price),
          allow_price_wave: parseFloat(row.input_wave_price),
        };

        const res = await updateLinePrice(submitData);

        // if (res.code === 200) {
        //   this.$message.success("价格更新成功");
        //   // 更新本地数据
        //   row.rec_price = row.input_rec_price;
        //   row.allow_price_wave = row.input_wave_price;
        //   // 更新主表格数据
        //   this.updateMainTableData(row);
        //   // 重新加载未定价线路数据
        //   this.fetchUnpricedRoutes();
        // } else {
        //   this.$message.error(res.msg || "提交价格失败");
        // }
      } catch (error) {
        // console.error("提交价格失败:", error);
        // this.$message.error("提交价格失败");
      } finally {
        row.submitting = false;
      }
    },

    // 更新主表格数据
    updateMainTableData (updatedRow) {
      const index = this.lineData.findIndex(item => item.id === updatedRow.id);
      if (index !== -1) {
        this.$set(this.lineData, index, {
          ...this.lineData[index],
          rec_price: updatedRow.input_rec_price,
          allow_price_wave: updatedRow.input_wave_price,
        });
      } else {
        // 如果主表格中没有这条数据，可以重新加载数据或添加到表格中
        this.fetchLineList();
      }
    },

    handlePageChange (currentPage) {
      this.page.currentPage = currentPage;
      this.fetchLineList();
    },

    handleSizeChange (pageSize) {
      this.page.pageSize = pageSize;
      this.page.currentPage = 1;
      this.fetchLineList();
    },

    handleUnpricedSizeChange (val) {
      this.unpricedPageSize = val;
      this.fetchUnpricedRoutes();
    },

    handleUnpricedCurrentChange (val) {
      this.unpricedCurrentPage = val;
      this.fetchUnpricedRoutes();
    },

    // 获取代理商列表数据
    async getAgentListData () {
      try {
        const res = await getAgentList({ page: 1, size: 1000 }); // 获取所有代理商
        if (res.err === 0) {
          let obj = {
            label: '无代理商',
            value: 0
          }
          this.agentList = [obj, ...res.data.map(item => ({
            label: item.realname,
            value: item.id
          }))];
        }
      } catch (error) {
        console.error('获取代理商列表失败:', error);
      }
    },

    onLoad (page) {
      this.page.currentPage = page.currentPage;
      this.page.pageSize = page.pageSize;
      this.fetchLineList();
    },
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.region-section {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

.line-section {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

.filter-area {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 8px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.line-search-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.line-search-input .line-separator {
  color: #606266;
  font-size: 14px;
  font-weight: bold;
}

.operation-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.new-btn {
  margin-right: 20px;
}

.search-info {
  margin-right: 20px;
  color: #1890ff;
  cursor: pointer;
}

.line-info {
  color: #909399;
}

.line-table-container {
  margin-top: 20px;
}

.line-items-table {
  margin-bottom: 20px;
}

.line-select-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.line-select {
  width: 150px;
}

.line-separator {
  margin: 0 10px;
  color: #606266;
}

.line-display {
  display: inline-block;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  min-width: 120px;
  text-align: center;
}

.type-display {
  display: inline-block;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  min-width: 120px;
  text-align: center;
}

.unpriced-routes-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .line-select {
    width: 120px;
  }

  .line-separator {
    margin: 0 5px;
  }
}
</style>
